import json
import time

from selenium import webdriver
from pynput.mouse import Button, Controller as c1
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC


class model:
    def InitialBrowser(self):
        # 驱动器地址
        f = r'/usr/bin/chromedriver'
        # f = r'E:\tool\other\chorme\chromedriver.exe'
        # chrome_options 初始化选项
        chrome_options = webdriver.ChromeOptions()
        # 设置浏览器初始 位置x,y & 宽高x,y
        chrome_options.add_argument(f'--window-position={0},{0}')
        chrome_options.add_argument(f'--window-size={1200},{1000}')
        # 关闭自动测试状态显示 // 会导致浏览器报：请停用开发者模式
        # window.navigator.webdriver还是返回True,当返回undefined时应该才可行。
        chrome_options.add_experimental_option("excludeSwitches", ['enable-automation'])
        # 关闭开发者模式
        chrome_options.add_experimental_option("useAutomationExtension", False)
        # 禁止图片加载
        prefs = {"profile.managed_default_content_settings.images": 2}
        chrome_options.add_experimental_option("prefs", prefs)
        # 设置中文
        chrome_options.add_argument('lang=zh_CN.UTF-8')
        # 更换头部
        chrome_options.add_argument(
            'user-agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36"')
        # 隐藏浏览器
        # chrome_options.add_argument('--headless')  # 隐藏浏览器
        # 部署项目在linux时，其驱动会要求这个参数
        chrome_options.add_argument('--no-sandbox')
        # 创建浏览器对象
        driver = webdriver.Chrome(f, options=chrome_options)
        # 设置执行js代码转换模式
        driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
            "source": """Object.defineProperty(navigator, 'webdriver', {get: () => undefined})""",
        })
        # 打开网站 测试
        # driver.get('https://www.baidu.com/')
        return driver

    # 滑块验证并自动登录
    def autoLogin(self, mobile, password):
        driver = self.InitialBrowser()
        mouse = c1()
        url = 'https://passport.tujia.com/PortalSite/LoginPage/?originUrl=https%3A%2F%2Fwww.tujia.com%2F'
        driver.get(url)
        # 滑动次数超过10次自动失败
        click = 0
        while True:
            mouse.position = (310, 570)
            # time.sleep(1)
            mouse.press(Button.left)
            mouse.move(400, 2)
            time.sleep(1)
            mouse.release(Button.left)
            WebDriverWait(driver, 5, 0.5).until(EC.presence_of_element_located((By.CLASS_NAME, 'nc-lang-cnt')))
            click += 1
            if click > 10 or driver.find_element_by_class_name('nc-lang-cnt').text == '验证通过':
                break

        element = driver.find_elements_by_css_selector(".form-item>input")
        key = 0
        for i in element:
            if key == 0:
                i.send_keys(mobile)
            if key == 1:
                i.send_keys(password)
            key += 1
        # time.sleep(1)
        submit_button = driver.find_element_by_class_name("submit")
        submit_button.click()
        return driver

    def get_name(self):
        print("hello")

    def save_cookies(self, mobile, password):
        driver = self.autoLogin(mobile, password)
        time.sleep(1)
        driver.get("https://guanjia.tujia.com/trademanagement/orderlist")
        time.sleep(1)
        cookies = driver.get_cookies()
        print(cookies)
        with open("../tmp_file/cookies_"+str(mobile)+".txt", "w") as fp:
            json.dump(cookies, fp)
        return cookies

if __name__ == "__main__":
    m = model()
    m.save_cookies(18510781868, "wc121369")
